package com.huatai.vba.integration.mail.impl;

import java.io.File;
import java.io.UnsupportedEncodingException;

import javax.mail.internet.MimeUtility;

import org.apache.commons.mail.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.huatai.vba.common.exception.BusinessException;
import com.huatai.vba.integration.mail.service.MailService;

@Service
public class MailServiceImpl implements MailService {

	private static final Logger logger = LoggerFactory.getLogger(MailService.class);

	@Value("hostName")
	private String hostName;

	@Value("userName")
	private String userName;

	@Value("password")
	private String password;

	@Value("charset")
	private String charset;

	@Value("fromEmail")
	private String fromEmail;

	@Value("maxLenght")
	private String maxLenght;

	public void sendEmail(String subject, String msg, String toEmail) throws BusinessException {
		sendEmail(subject, msg, new String[] { toEmail });
	}

	public void sendEmail(String subject, String msg, String... toEmails) throws BusinessException {
		sendEmail(subject, msg, toEmails);
	}

	public void sendEmail(String subject, String msg, File file, String toEmail) throws BusinessException {
		sendEmail(subject, msg, new File[] { file }, new String[] { toEmail });
	}

	public void sendEmail(String subject, String msg, File[] files, String[] toEmails) throws BusinessException {
		Email email = null;
		try {
			if (files == null || files.length == 0) {
				email = new SimpleEmail();
			} else {
				email = new MultiPartEmail();
				for (File f : files) {
					if (f.length() > Long.valueOf(maxLenght))
						((MultiPartEmail) email).attach(convert(f));
				}
			}
			email.setHostName(hostName);
			email.setAuthentication(userName, password);
			email.setCharset(charset);

			email.setFrom(fromEmail);
			email.setSubject(subject);
			if (toEmails == null || toEmails.length == 0) {
				throw new BusinessException("目标邮件地址为空");
			}
			for (String toEmail : toEmails) {
				email.addTo(toEmail);
			}
			email.setMsg(msg);
			email.send();
		} catch (UnsupportedEncodingException ex) {
			logger.error("邮件发送失败,编码不支持", ex);
			throw new BusinessException("邮件发送失败");
		} catch (EmailException e) {
			logger.error("邮件发送失败", e);
			throw new BusinessException("邮件发送失败");
		}
	}

	private EmailAttachment convert(File f) throws UnsupportedEncodingException {
		if (!f.exists())
			return null;
		EmailAttachment ea = new EmailAttachment();
		ea.setName(MimeUtility.encodeText(f.getName()));
		ea.setPath(f.getPath());
		ea.setDescription(null);
		ea.setDisposition(EmailAttachment.ATTACHMENT);
		return ea;
	}
}
